package controller

import (
    "encoding/json"
    "github.com/wubo19842008/gowxtks/server/config"
    "github.com/wubo19842008/gowxtks/server/token"
    "github.com/wubo19842008/gowxtks/utils"
    "io"
    "log"
    "net/http"
)

const (
    TOKEN_GW_MP string = "https://api.weixin.qq.com/cgi-bin/token" +
        "?grant_type=client_credential"
    TOKEN_GW_CP string = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?"
)

type TokenCtrl struct {
    Config map[string]config.WxConfig
}

func (c *TokenCtrl) Get(rw http.ResponseWriter, req *http.Request) {
    log.Println(c.Config)
    req.ParseForm()
    aid := req.FormValue("aid")

    log.Printf("aid is %s", aid)
    io.WriteString(rw, token.GetToken(aid))
}

func (c *TokenCtrl) Refresh(rw http.ResponseWriter, req *http.Request) {
    req.ParseForm()
    aid := req.FormValue("aid")
    log.Printf("aid is %s", aid)

    cfg := c.Config[aid]
    url := TOKEN_GW_MP +
        "&appid=" + cfg.AppId +
        "&secret=" + cfg.AppSec
    if cfg.WxType == config.WX_CP {
        url = TOKEN_GW_CP +
            "corpid=" + cfg.AppId +
            "&corpsecret=" + cfg.AppSec
    }

    rr := utils.DoGet(url)

    var _token token.WxToken
    json.Unmarshal(rr, &_token)
    token.SetToken(aid, _token.AccessToken)
    io.WriteString(rw, _token.AccessToken)
}
